package com.atguigu.yygh.oss.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.atguigu.yygh.common.utils.R;
import com.atguigu.yygh.oss.properties.OssProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@Api(tags = "oss的接口")
@RequestMapping("/admin/oss/file")
@EnableConfigurationProperties(OssProperties.class)
public class FileController {

    @Autowired
    private OssProperties ossProperties;

    @ApiOperation("上传文件")
    @PostMapping("/unload")
    private R unload(MultipartFile file) throws IOException {


        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://"+ossProperties.getEndpoint();
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        //EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        String accessKeyId=ossProperties.getKeyid();
        String accessKeySecret=ossProperties.getKeysecret();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ossProperties.getBucketname();
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String date = new DateTime().toString("yyyy/MM/dd");
        String uuid = new DateTime().toString().replaceAll("-", "");
        String filename = file.getOriginalFilename();
        String objectName=date+uuid+filename;

        //上传的文件
        InputStream inputStream = file.getInputStream();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
        ossClient.putObject(putObjectRequest);


        ossClient.shutdown();

        String url="https://%s.%s/%s";

        url=String.format(url, bucketName,ossProperties.getEndpoint(),objectName);

        return R.ok().data("url",url);
    }

}
